// 模型管理页面
import React, { useState, useEffect } from 'react';
import { Layout, Card, Table, Button, message, Space, Typography, Tag, Divider, Form, Input, Select, Tabs } from 'antd';
import { DownloadOutlined, DeleteOutlined, EditOutlined, BarChartOutlined } from '@ant-design/icons';
import { mockService } from '../services/mockService';
import type { Model, Job } from '../types';
import { formatDateTime } from '../utils/fileUtils';

const { Content } = Layout;
const { Text } = Typography;
const { Option } = Select;

const ModelsPage: React.FC = () => {
  const [models, setModels] = useState<Model[]>([]);
  const [jobs, setJobs] = useState<Job[]>([]);
  const [loading, setLoading] = useState(false);
  // 编辑模型状态将在后续功能中使用
  const [modelForm] = Form.useForm();
  const [activeTab, setActiveTab] = useState<string>('list');

  // 加载数据
  useEffect(() => {
    loadInitialData();
  }, []);

  const loadInitialData = async () => {
    try {
      setLoading(true);
      // 加载模型
      const modelsRes = await mockService.models.getAll();
      if (modelsRes.success && modelsRes.data) {
        setModels(modelsRes.data);
      }
      // 加载已完成的作业用于创建模型
      const jobsRes = await mockService.jobs.getAll();
      if (jobsRes.success && jobsRes.data) {
        setJobs(jobsRes.data.filter(job => job.status === 'completed' && job.metrics));
      }
    } catch (error) {
      message.error('数据加载失败');
      console.error('加载错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 处理模型保存
  const handleModelSave = async (values: any) => {
    try {
      setLoading(true);
      
      const selectedJob = jobs.find(job => job.id === values.jobId);
      if (!selectedJob || !selectedJob.metrics) {
        message.error('请选择有效的作业');
        return;
      }

      // 检查是否已存在相同名称和版本的模型
      const duplicate = models.find(
        model => model.name === values.name && model.version === parseInt(values.version)
      );
      
      if (duplicate) {
        message.error('已存在相同名称和版本的模型，请修改版本号');
        return;
      }

      const modelData = {
        name: values.name,
        version: parseInt(values.version),
        description: values.description,
        jobId: values.jobId,
        metrics: selectedJob.metrics,
        config: selectedJob.modelConfig
      };

      const response = await mockService.models.save(modelData);
      
      if (response.success && response.data) {
        setModels(prev => [...prev, response.data as Model]);
        message.success('模型保存成功！');
        modelForm.resetFields();
      } else {
        message.error(response.error || '模型保存失败');
      }
    } catch (error) {
      message.error('模型保存失败，请重试');
      console.error('错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 删除模型
  const handleDeleteModel = (id: string) => {
    setModels(prev => prev.filter(model => model.id !== id));
    message.success('模型删除成功');
  };

  // 下载模型
  const handleDownloadModel = (model: Model) => {
    message.success(`正在下载模型：${model.name}`);
    // 实际项目中这里会有模型文件的下载逻辑
  };

  // 渲染模型列表
  const renderModelList = () => (
    <Card title="模型列表" extra={<Button type="primary" onClick={() => setActiveTab('save')}>保存新模型</Button>}>
      <Table
        dataSource={models}
        columns={[
          { title: '模型名称', dataIndex: 'name', key: 'name' },
          { title: '版本', dataIndex: 'version', key: 'version' },
          { title: '模型类型', dataIndex: ['config', 'modelType'], key: 'modelType' },
          { 
            title: '准确率', 
            dataIndex: ['metrics', 'accuracy'], 
            key: 'accuracy',
            render: (accuracy) => accuracy ? `${(accuracy * 100).toFixed(2)}%` : '-' 
          },
          { 
            title: 'F1分数', 
            dataIndex: ['metrics', 'f1Score'], 
            key: 'f1Score',
            render: (f1) => f1 ? f1.toFixed(4) : '-' 
          },
          { 
            title: '创建时间', 
            dataIndex: 'createdAt', 
            key: 'createdAt',
            render: (time) => formatDateTime(time)
          },
          { 
            title: '操作', 
            key: 'action', 
            render: (_, record) => (
              <Space>
                <Button type="link" icon={<DownloadOutlined />} onClick={() => handleDownloadModel(record)}>下载</Button>
                <Button type="link" icon={<EditOutlined />} onClick={() => message.info('编辑功能开发中')}>编辑</Button>
                <Button type="link" danger icon={<DeleteOutlined />} onClick={() => handleDeleteModel(record.id)}>删除</Button>
                <Button type="link" icon={<BarChartOutlined />} onClick={() => setActiveTab('comparison')}>对比</Button>
              </Space>
            )
          }
        ]}
        rowKey="id"
        loading={loading}
        expandable={{
          expandedRowRender: (model) => (
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Text strong>描述：</Text>
                <Text>{model.description}</Text>
              </div>
              <div>
                <Text strong>评估指标：</Text>
                <Space wrap>
                  {model.metrics && Object.entries(model.metrics).map(([key, value]) => (
                    <Tag key={key} color="blue">
                      {key}: {value?.toFixed(4)}
                    </Tag>
                  ))}
                </Space>
              </div>
              <div>
                <Text strong>模型配置：</Text>
                <pre style={{ background: '#f5f5f5', padding: '12px', borderRadius: '4px', overflow: 'auto' }}>
                  {JSON.stringify(model.config, null, 2)}
                </pre>
              </div>
            </Space>
          ),
          rowExpandable: () => true,
        }}
      />
    </Card>
  );

  // 渲染模型保存表单
  const renderModelSaveForm = () => (
    <Card title="保存模型" extra={<Button onClick={() => setActiveTab('list')}>返回列表</Button>}>
      <Form
        form={modelForm}
        layout="vertical"
        onFinish={handleModelSave}
        style={{ maxWidth: '800px' }}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <Form.Item name="jobId" label="选择完成的作业" rules={[{ required: true, message: '请选择作业' }]}>
            <Select placeholder="请选择已完成的训练作业">
              {jobs.map(job => (
                <Option key={job.id} value={job.id}>
                  {job.name} ({job.modelConfig.modelType}) - 准确率: {(job.metrics?.accuracy || 0) * 100}%
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item name="name" label="模型名称" rules={[{ required: true, message: '请输入模型名称' }]}>
            <Input placeholder="请输入模型名称" />
          </Form.Item>

          <Form.Item name="version" label="版本号" rules={[{ required: true, message: '请输入版本号' }]}>
            <Input placeholder="请输入版本号" type="number" min={1} />
          </Form.Item>

          <Form.Item name="description" label="模型描述">
            <Input.TextArea rows={3} placeholder="请输入模型描述" />
          </Form.Item>

          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => setActiveTab('list')}>取消</Button>
            <Button type="primary" htmlType="submit" loading={loading} style={{ marginLeft: '12px' }}>
              保存模型
            </Button>
          </div>
        </Space>
      </Form>
    </Card>
  );

  // 渲染模型对比
  const renderModelComparison = () => (
    <Card title="模型对比" extra={<Button onClick={() => setActiveTab('list')}>返回列表</Button>}>
      {models.length === 0 ? (
        <Text type="secondary">暂无模型可对比</Text>
      ) : (
        <div>
          <Text strong>请选择要对比的模型（最多选择3个）</Text>
          <Divider />
          <div style={{ height: '400px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Text type="secondary">模型对比图表展示区域</Text>
          </div>
        </div>
      )}
    </Card>
  );

  return (
    <Layout className="layout">
      <Content style={{ padding: '24px', minHeight: 'calc(100vh - 64px)' }}>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <Tabs.TabPane tab="模型列表" key="list">
            {renderModelList()}
          </Tabs.TabPane>
          <Tabs.TabPane tab="保存模型" key="save">
            {renderModelSaveForm()}
          </Tabs.TabPane>
          <Tabs.TabPane tab="模型对比" key="comparison">
            {renderModelComparison()}
          </Tabs.TabPane>
        </Tabs>
      </Content>
    </Layout>
  );
};

export default ModelsPage;